<template>
  <div class="coupon-page">
    <Header :scroll="scroll" />

    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">优惠券中心</h1>
        <p class="page-subtitle">精选优惠券，让您享受更多实惠</p>
      </div>
    </div>

    <!-- 优惠券筛选区域 -->
    <div class="coupon-filter">
      <div class="container">
        <div class="filter-tabs">
          <div class="filter-tab" :class="{ active: activeTab === 'all' }" @click="setActiveTab('all')">全部优惠券</div>
          <div class="filter-tab" :class="{ active: activeTab === 'available' }" @click="setActiveTab('available')">可领取</div>
          <div class="filter-tab" :class="{ active: activeTab === 'received' }" @click="setActiveTab('received')">已领取</div>
          <div class="filter-tab" :class="{ active: activeTab === 'used' }" @click="setActiveTab('used')">已使用</div>
          <div class="filter-tab" :class="{ active: activeTab === 'expired' }" @click="setActiveTab('expired')">已过期</div>
        </div>
      </div>
    </div>

    <!-- 优惠券列表 -->
    <div class="coupon-content">
      <div class="container">
        <div class="coupon-grid" v-infinite-scroll="loadMore" :infinite-scroll-disabled="disabled">
          <div
            v-for="(coupon, index) in coupons"
            :key="index"
            class="coupon-card"
            :class="{
              received: coupon.received > 0,
              used: coupon.coupon_status === 5,
              expired: coupon.coupon_status === 3,
            }">
            <div class="coupon-left">
              <div class="coupon-amount" v-if="coupon.content_type === 1">
                <span class="value">{{ coupon.discount }}</span>
                <span class="currency">折</span>
              </div>
              <div class="coupon-amount" v-else>
                <span class="currency">¥</span>
                <span class="value">{{ coupon.coupon_amount }}</span>
              </div>
              <div class="coupon-condition" v-if="coupon.content_type === 1">满{{ coupon.threshold }}元可用</div>
              <div class="coupon-condition" v-else-if="coupon.content_type === 2">商品立减券</div>
              <div class="coupon-condition" v-else-if="coupon.content_type === 3">商品折扣券</div>
            </div>
            <div class="coupon-right">
              <div class="coupon-info">
                <h3 class="coupon-title">{{ coupon.coupon_name }}</h3>
                <p class="coupon-desc">{{ coupon.coupon_scene }}</p>
                <div class="coupon-validity">
                  <span class="validity-label">有效期：</span>
                  <span class="validity-date">{{ formatDate(coupon.coupon_end_time) }}</span>
                </div>
              </div>
              <div class="coupon-action">
                <button v-if="canReceiveCoupon(coupon)" class="coupon-btn receive-btn" @click="receiveCoupon(coupon)">立即领取</button>
                <button v-else-if="coupon.received > 0 && coupon.coupon_status === 2" class="coupon-btn use-btn" @click="useCoupon(index)">
                  立即使用
                </button>
                <span v-else-if="coupon.coupon_status === 5" class="coupon-status used-status"> 已使用 </span>
                <span v-else-if="coupon.coupon_status === 3" class="coupon-status expired-status"> 已过期 </span>
              </div>
            </div>
            <div class="coupon-decoration">
              <div class="decoration-circle top"></div>
              <div class="decoration-circle bottom"></div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="recordCount === 0" class="empty-state">
          <div class="empty-icon">
            <img src="@/assets/images/cart-green.png" alt="暂无优惠券" class="empty-image" />
          </div>
          <p class="empty-text">暂无相关优惠券</p>
          <p class="empty-desc">快去商城逛逛，获取更多优惠券吧</p>
          <button class="go-shopping-btn" @click="goShopping">去购物</button>
        </div>
      </div>
    </div>

    <!-- 页脚 -->
    <Footer />
  </div>
</template>

<script setup>
  import { getCurrentInstance, ref, computed, onMounted } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import Header from '@/components/Header.vue'
  import Footer from '@/components/Footer.vue'
  import { useUserStore } from '@/stores/user.js'
  import apiCoupon from '@/api/modules/coupon'
  import apiUser from '@/api/modules/user'

  const router = useRouter()
  const route = useRoute()
  const userStore = useUserStore()
  const { proxy } = getCurrentInstance()
  const scroll = ref(false)

  // 监听滚动
  window.addEventListener('scroll', () => {
    scroll.value = window.scrollY > 0
  })

  // 当前激活的标签
  const activeTab = ref('all')
  const getTabStatus = (tab) => {
    const statusMap = {
      all: 0, // 平台全部
      available: 2, // 平台可用
      received: 0, // 已领取
      used: 5, // 用户已使用
      expired: 3, // 用户已过期
    }
    return statusMap[tab] || 0
  }

  // 当前用户的状态
  const recvCondition = ref({
    isNewUser: false,
    isComment: false,
    isBirthday: false,
  })

  const canReceiveCoupon = (coupon) => {
    if (coupon.received >= coupon.coupon_max_apply_times) return false
    if (coupon.coupon_status !== 2) return false
    if (coupon.available_num === 0) return false
    if (coupon.coupon_type == 1 && !recvCondition.value.isNewUser) return false
    if (coupon.coupon_type == 2 && recvCondition.value.isNewUser) return false
    if (coupon.coupon_type == 3 && !recvCondition.value.isComment) return false
    if (coupon.coupon_type == 4 && !recvCondition.value.isBirthday) return false
    return true
  }

  // 优惠券数据
  const coupons = ref([])

  // 设置激活标签
  const setActiveTab = (tab) => {
    activeTab.value = tab
    fetchData(1)
  }

  // 领取优惠券
  const receiveCoupon = (coupon) => {
    if (!canReceiveCoupon(coupon)) {
      return
    }

    apiCoupon.ReceiveCoupon({ coupon_id: coupon.id }).then((res) => {
      // 更新优惠券状态
      coupon.received++
      coupon.available_num = Math.max(0, coupon.available_num - 1)
      ElMessage.success(res.msg)
    })
  }

  // 使用优惠券
  const useCoupon = (index) => {
    // 跳转到商城页面
    router.push('/')
    window.scrollTo(0, 0)
  }

  // 去购物
  const goShopping = () => {
    router.push('/')
    window.scrollTo(0, 0)
  }

  // 数据分页查询
  const recordCount = ref(0)
  const page = ref(1)
  const limit = ref(6)

  // 是否正在加载
  const loading = ref(false)
  // 是否还有更多数据
  const hasMore = ref(true)
  // 计算属性 - 是否禁用无限滚动
  const disabled = computed(() => loading.value || !hasMore.value)
  // 计算属性 - 是否没有更多数据
  const noMore = computed(() => !hasMore.value && coupons.value.length > 0)

  // 分页加载数据
  const fetchData = async (currentPage) => {
    if (loading.value) {
      return
    }
    loading.value = true
    const status = getTabStatus(activeTab.value)
    if (['all', 'available'].includes(activeTab.value)) {
      apiCoupon
        .GetCouponList({ page: currentPage, limit: limit.value, coupon_status: status })
        .then(async (res) => {
          loading.value = false
          recordCount.value = res.count
          page.value = currentPage
          hasMore.value = currentPage * limit.value < recordCount.value
          if (page.value === 1) {
            coupons.value = res.data
          } else {
            coupons.value = [...coupons.value, ...res.data]
          }
        })
        .catch((err) => {
          loading.value = false
        })
    } else {
      apiUser
        .GetCouponList({ page: currentPage, limit: limit.value, coupon_status: status })
        .then(async (res) => {
          loading.value = false
          recordCount.value = res.count
          page.value = currentPage
          hasMore.value = currentPage * limit.value < recordCount.value
          res.data.forEach((item) => {
            item.received = 1
          })
          if (page.value === 1) {
            coupons.value = res.data
          } else {
            coupons.value = [...coupons.value, ...res.data]
          }
        })
        .catch((err) => {
          loading.value = false
        })
    }
  }

  // 加载更多数据
  const loadMore = () => {
    if (!disabled.value) {
      fetchData(page.value + 1)
    }
  }

  // 加载用户领取资格
  const loadUserRecvCondition = () => {
    apiCoupon.GetUserRecvCondition().then((res) => {
      recvCondition.value = res.data
    })
  }

  // 初始化
  onMounted(() => {
    loadUserRecvCondition()
    fetchData(1)
  })

  const formatDate = (date) => {
    try {
      const newDate = new Date(date)
      const year = newDate.getFullYear()
      const month = String(newDate.getMonth() + 1).padStart(2, '0')
      const day = String(newDate.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    } catch (error) {
      return ''
    }
  }
</script>

<style scoped>
  .coupon-page {
    width: 100%;
    min-height: 100vh;
    background-color: #ffffff;
  }

  /* 页面标题区域 */
  .page-header {
    background: linear-gradient(135deg, #52a58a 0%, #459a7e 100%);
    padding: 60px 0;
    color: white;
    text-align: center;
  }

  .page-title {
    font-size: 32px;
    font-weight: 600;
    margin: 0 0 15px 0;
  }

  .page-subtitle {
    font-size: 16px;
    margin: 0;
    opacity: 0.9;
  }

  /* 筛选区域 */
  .coupon-filter {
    background: white;
    padding: 30px 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }

  .filter-tabs {
    display: flex;
    justify-content: center;
    gap: 40px;
  }

  .filter-tab {
    padding: 12px 24px;
    border-radius: 25px;
    background: #f8f9fa;
    color: #666;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 15px;
    font-weight: 500;
  }

  .filter-tab:hover {
    background: #e9ecef;
    color: #333;
  }

  .filter-tab.active {
    background: #52a58a;
    color: white;
  }

  /* 优惠券内容区域 */
  .coupon-content {
    padding: 40px 0;
  }

  .coupon-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
    gap: 25px;
    margin-bottom: 40px;
  }

  /* 优惠券卡片 */
  .coupon-card {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    position: relative;
    display: flex;
    min-height: 140px;
  }

  .coupon-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
  }

  .coupon-card.received {
    border: 2px solid #52a58a;
  }

  .coupon-card.used {
    opacity: 0.6;
    background: #f8f9fa;
  }

  .coupon-card.expired {
    opacity: 0.5;
    background: #f8f9fa;
  }

  /* 优惠券左侧 */
  .coupon-left {
    background: linear-gradient(135deg, #52a58a 0%, #459a7e 100%);
    color: white;
    padding: 30px 25px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    min-width: 150px;
    position: relative;
  }

  .coupon-amount {
    display: flex;
    align-items: baseline;
    margin-bottom: 8px;
  }

  .currency {
    font-size: 18px;
    font-weight: 500;
  }

  .value {
    font-size: 36px;
    font-weight: 700;
    margin-left: 2px;
  }

  .coupon-condition {
    font-size: 13px;
    opacity: 0.9;
    text-align: center;
  }

  /* 优惠券右侧 */
  .coupon-right {
    flex: 1;
    padding: 25px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .coupon-info {
    flex: 1;
  }

  .coupon-title {
    font-size: 18px;
    color: #333;
    margin: 0 0 8px 0;
    font-weight: 600;
  }

  .coupon-desc {
    font-size: 14px;
    color: #666;
    margin: 0 0 12px 0;
    line-height: 1.4;
  }

  .coupon-validity {
    font-size: 13px;
    color: #999;
  }

  .validity-label {
    margin-right: 5px;
  }

  .validity-date {
    color: #e53935;
    font-weight: 500;
  }

  /* 优惠券操作 */
  .coupon-action {
    margin-left: 20px;
  }

  .coupon-btn {
    padding: 10px 20px;
    border: none;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    min-width: 80px;
  }

  .receive-btn {
    background: #52a58a;
    color: white;
  }

  .receive-btn:hover {
    background: #459a7e;
    transform: translateY(-1px);
  }

  .use-btn {
    background: #ff6b35;
    color: white;
  }

  .use-btn:hover {
    background: #e55a2b;
    transform: translateY(-1px);
  }

  .coupon-status {
    padding: 8px 16px;
    border-radius: 15px;
    font-size: 13px;
    font-weight: 500;
  }

  .used-status {
    background: #e9ecef;
    color: #6c757d;
  }

  .expired-status {
    background: #ffebee;
    color: #e53935;
  }

  /* 装饰圆圈 */
  .coupon-decoration {
    position: absolute;
    right: 150px;
    top: 0;
    bottom: 0;
    width: 0;
  }

  .decoration-circle {
    position: absolute;
    width: 20px;
    height: 20px;
    background: #f5f5f5;
    border-radius: 50%;
    right: -10px;
  }

  .decoration-circle.top {
    top: -10px;
  }

  .decoration-circle.bottom {
    bottom: -10px;
  }

  /* 空状态 */
  .empty-state {
    text-align: center;
    padding: 80px 20px;
  }

  .empty-icon {
    margin-bottom: 30px;
  }

  .empty-image {
    width: 120px;
    height: 120px;
    opacity: 0.3;
  }

  .empty-text {
    font-size: 18px;
    color: #333;
    margin-bottom: 10px;
  }

  .empty-desc {
    font-size: 14px;
    color: #999;
    margin-bottom: 30px;
  }

  .go-shopping-btn {
    background: #52a58a;
    color: white;
    border: none;
    padding: 12px 30px;
    border-radius: 25px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  .go-shopping-btn:hover {
    background: #459a7e;
  }

  /* 响应式设计 */
  @media (max-width: 1024px) {
    .coupon-grid {
      grid-template-columns: 1fr;
      gap: 20px;
    }

    .filter-tabs {
      gap: 20px;
    }

    .filter-tab {
      padding: 10px 20px;
      font-size: 14px;
    }
  }

  @media (max-width: 768px) {
    .page-header {
      padding: 40px 0;
    }

    .page-title {
      font-size: 24px;
    }

    .page-subtitle {
      font-size: 14px;
    }

    .coupon-filter {
      padding: 20px 0;
    }

    .filter-tabs {
      flex-wrap: wrap;
      gap: 10px;
      justify-content: center;
    }

    .filter-tab {
      padding: 8px 16px;
      font-size: 13px;
    }

    .coupon-content {
      padding: 30px 0;
    }

    .coupon-grid {
      gap: 15px;
    }

    .coupon-card {
      flex-direction: column;
      min-height: auto;
    }

    .coupon-left {
      min-width: auto;
      padding: 20px;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      gap: 15px;
    }

    .coupon-amount {
      margin-bottom: 0;
    }

    .value {
      font-size: 28px;
    }

    .coupon-condition {
      font-size: 12px;
    }

    .coupon-right {
      padding: 20px;
      flex-direction: column;
      align-items: stretch;
    }

    .coupon-action {
      margin-left: 0;
      margin-top: 15px;
      text-align: center;
    }

    .coupon-btn {
      width: 100%;
      padding: 12px;
    }

    .decoration-circle {
      display: none;
    }

    .empty-state {
      padding: 60px 15px;
    }

    .empty-image {
      width: 100px;
      height: 100px;
    }
  }

  @media (max-width: 480px) {
    .page-header {
      padding: 30px 0;
    }

    .page-title {
      font-size: 20px;
    }

    .page-subtitle {
      font-size: 13px;
    }

    .filter-tabs {
      gap: 8px;
    }

    .filter-tab {
      padding: 6px 12px;
      font-size: 12px;
    }

    .coupon-content {
      padding: 20px 0;
    }

    .coupon-card {
      border-radius: 8px;
    }

    .coupon-left {
      padding: 15px;
      gap: 10px;
    }

    .value {
      font-size: 24px;
    }

    .currency {
      font-size: 16px;
    }

    .coupon-condition {
      font-size: 11px;
    }

    .coupon-right {
      padding: 15px;
    }

    .coupon-title {
      font-size: 16px;
    }

    .coupon-desc {
      font-size: 13px;
    }

    .coupon-validity {
      font-size: 12px;
    }

    .coupon-action {
      margin-top: 12px;
    }

    .coupon-btn {
      padding: 10px;
      font-size: 13px;
    }

    .empty-state {
      padding: 40px 10px;
    }

    .empty-text {
      font-size: 16px;
    }

    .empty-desc {
      font-size: 13px;
    }

    .go-shopping-btn {
      padding: 10px 25px;
      font-size: 14px;
    }
  }
</style>
